<template>
  <view>
    <view class="content">
      <view class="row">
        <view class="nominal">收件人</view>
        <view class="input">
          <input placeholder="请输入收件人姓名" type="text" v-model="name" />
        </view>
      </view>
      <view class="row">
        <view class="nominal">电话号码</view>
        <view class="input">
          <input placeholder="请输入收件人电话号码" type="text" v-model="tel" />
        </view>
      </view>
      <view class="row">
        <view class="nominal">所在地区</view>
        <view class="input" @tap="chooseCity">{{region.label}}</view>
      </view>
      <view class="row">
        <view class="nominal">详细地址</view>
        <view class="input">
          <textarea v-model="detailed" auto-height="true" placeholder="输入详细地址"></textarea>
        </view>
      </view>
      <view class="row">
        <view class="nominal">设置默认地址</view>
        <view class="input switch">
          <switch color="#354E44" :checked="isDefault" @change="isDefaultChange" />
        </view>
      </view>
      <view class="row last" v-if="editType" @tap="del">
        <view class="del">删除收货地址</view>
      </view>
    </view>
    <view class="save" @tap="save1">
      <view class="btn">保存地址</view>
    </view>
	<simple-address ref="simpleAddress" :pickerValueDefault="cityPickerValueDefault" @onConfirm="onConfirm" themeColor="#007AFF"></simple-address>
   <!-- <mpvue-city-picker
      :themeColor="themeColor"
      ref="mpvueCityPicker"
      :pickerValueDefault="cityPickerValue"
      @onCancel="onCancel"
      @onConfirm="onConfirm"
    ></mpvue-city-picker> -->
  </view>
</template>

<script>
//插件市场:  https://ext.dcloud.net.cn/plugin?id=115  
import mpvueCityPicker from "@/components/mpvue-citypicker/mpvueCityPicker.vue";
import addressApi from "@/api/mine/address.js";
export default {
  name: "AddressEdit",
  components: {
    mpvueCityPicker
  },
  data() {
    return {
	cityPickerValueDefault: [0, 0, 1],
      editType: false,
      id: "",
      name: "",
      tel: "",
      detailed: "",
      isDefault: false,
      cityPickerValue: [0,0,0],
	  addressid:"",
      themeColor: "#007AFF",
      region: { label: "请点击选择地址", value: [], cityCode: "" },
      address: {},
	  addressInfo:{}
    };
  },
  methods: {
    onCancel(e) {
    },
    chooseCity() {
		this.$refs.simpleAddress.open();
      // this.$refs.mpvueCityPicker.show();
    },
    onConfirm(e) {
	  this.region.cityCode = `${e.provinceCode}-${e.cityCode}-${e.areaCode}`;
	  this.region.label = e.labelArr.join("-");
	  this.region.value = e.labelArr;
   //    this.region = e;
	  // // 预存 一个 values 
   //    this.cityPickerValue = e.value;
    },
    isDefaultChange(e) {
      this.isDefault = e.detail.value;
	  if(this.editType){
		  addressApi.switchDefault(this.addressid,e.detail.value == true?1:0)
		  .then(res =>{
			  if(res.success == true){
				  uni.showToast({
				  	title:"切换默认成功",
					icon:"none"
				  })
			  }
		  })
	  }
    },
    del() {
      uni.showModal({
        title: "删除提示",
        content: "你将删除这个收货地址",
        success: res => {
          if (res.confirm) {
            // 发送请求删除地址
			addressApi.delAddressInfo(this.addressInfo.id)
			.then(res =>{
				if(res.success == true){
					uni.showToast({
						title:"删除成功"
					});
					setTimeout(()=>{
						uni.navigateBack({
							delta:1
						})
					},1000)
					
				}
			})
          } else if (res.cancel) {
          }
        }
      });
    }, 
	save1(){
		if (!this.name) {
		  uni.showToast({ title: "请输入收件人姓名", icon: "none" });
		  return;
		}
		if (!this.tel) {
		  uni.showToast({ title: "请输入收件人电话号码", icon: "none" });
		  return;
		}
		if (this.region.value.length == 0) {
		  uni.showToast({ title: "请选择收件地址", icon: "none" });
		  return;
		}
		if (!this.detailed) {
		  uni.showToast({ title: "请输入收件人详细地址", icon: "none" });
		  return;
		}
		
		uni.showLoading({
		  title: "正在提交"
		});
		const obj = {
			  "city": this.region.value[1],
			  "cityCode": this.region.cityCode,
			  "defaultStatus": this.isDefault ? 1 : 0,
			  "detailAddress": this.detailed,
			  "name": this.name,
			  "phoneNumber": this.tel,
			  "postCode": "",
			  "province": this.region.value[0],
			  "region": this.region.value[2],
			  "tag": ""
			}
		if(this.editType){ // 编辑
			obj.memberId = this.addressInfo.memberId;
			obj.id = this.addressInfo.id
			addressApi.updateAddressInfo(obj)
			.then(res =>{
				if(res.success == true){
					uni.showToast({
						title:"更新成功"
					});
					setTimeout(()=>{
						uni.navigateBack({
							delta:1
						})
					},1000)
				}
			})
			
		}else{ // 新增
			
			addressApi.addAddressInfo(obj)	
			.then(res =>{
				if(res.success == true){
					uni.showToast({
						title:"添加成功"
					})
					setTimeout(()=>{
						uni.navigateBack({
							delta:1
						})
					},1000)
				}
			})
		}
	},
    save() {
      let data = {
        name: this.name,
        tel: this.tel,
        address: { region: this.region, detailed: this.detailed },
        isDefault: this.isDefault
      };
      if (this.editType == "edit") {
        data.id = this.id;
      }
      if (!data.name) {
        uni.showToast({ title: "请输入收件人姓名", icon: "none" });
        return;
      }
      if (!data.tel) {
        uni.showToast({ title: "请输入收件人电话号码", icon: "none" });
        return;
      }
      if (!data.address.detailed) {
        uni.showToast({ title: "请输入收件人详细地址", icon: "none" });
        return;
      }
      if (data.address.region.value.length == 0) {
        uni.showToast({ title: "请选择收件地址", icon: "none" });
        return;
      }
      uni.showLoading({
        title: "正在提交"
      });
      // 构建可提交内容  吧cityCode和value拼接一块
	  // cityCode: "130203"  value: [2,1,1]  ==>  130203,2,1,1
      var cityCodeArr = [];
      cityCodeArr[0] = this.region.cityCode;  // [130203]
      for (var i = 0; i < this.region.value.length; i++) {
        cityCodeArr.push(this.region.value[i]); //[130203,2,1,1]
      }
	  var postData = {
		  userId: this.$store.getters.userId,
          tag: "家",
          name: data.name,
          tel: data.tel,
          cityCode: cityCodeArr.join(),  //[130203,2,1,1].join() => '130203,2,1,1'
		  cityStr: this.region.label, // "北京市-市辖区-东城区"
		  cityBak: this.detailed, // 搜狐大厦101
		  isUse: this.isDefault?1:0 // 是否默认
        };
		// {
		//   "city":  this.region.label,
		//   "cityCode": cityCodeArr.join(),
		//   "defaultStatus": this.isDefault?1:0,
		//   "detailAddress": this.detailed,
		//   "id": "string",
		//   "memberId": "string",
		//   "name": data.name,
		//   "phoneNumber": data.tel,
		//   "postCode": "",
		//   "province": "string",
		//   "region": "string",
		//   "tag": "string"
		// }
	  var api = null;
	  // 根据当前数据是否有id 判断是新增操作还是更新操作
	  if(this.id){
		  api = addressApi.addressUpdate;
		  postData.id = this.id;
	  }else{
		  api = addressApi.addressSave;
	  }
      api(postData)
        .then(res => {
			if(res.code == 'S'){
				uni.showToast({
					title:'保存成功!',
					duration:1000
				})
				uni.navigateTo({
					url:'../index'
				})
			}else{
				uni.showToast({
					title: '保存失败!',
					duration:1000
				})
			}
		});
    },
	// 根据id获取地址明细
	getAddressById(id){
		addressApi.addressList()
		.then(res =>{
			var info = res.data.items.find(ele =>ele.id == id);
			this.addressInfo = info;
			this.name = info.name;
			this.tel = info.name;
			this.region = {
				cityCode:info.cityCode,
				label:`${info.province}-${info.city}-${info.region}`,
				value:[info.province,info.city,info.region]
			};
			this.detailed = info.detailAddress;
			this.isDefault = info.defaultStatus ? true : false;
		})
	}
  },
  onLoad(e) {
	// 如果有addressId 说明是编辑 
	if(e.addressId){
		this.editType = true;
		this.addressid = e.addressId;
		this.getAddressById(e.addressId);
	}else{
		this.editType = false
	}
	
  },
  // onBackPress() {
  //   if (this.$refs.mpvueCityPicker.showPicker) {
  //     this.$refs.mpvueCityPicker.pickerCancel();
  //     return true;
  //   }
  // },
  onUnload() {
    if (this.$refs.mpvueCityPicker.showPicker) {
      this.$refs.mpvueCityPicker.pickerCancel();
    }
  }
};
</script>
<style lang="scss" scoped>
.save {
  view {
    display: flex;
  }
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 120upx;
  display: flex;
  justify-content: center;
  align-items: center;
  .btn {
    box-shadow: 0upx 5upx 10upx rgba(0, 0, 0, 0.4);
    width: 70%;
    height: 80upx;
    border-radius: 80upx;
    background-color: #354E44;
    color: #fff;
    justify-content: center;
    align-items: center;
    .icon {
      height: 80upx;
      color: #fff;
      font-size: 30upx;
      justify-content: center;
      align-items: center;
    }
    font-size: 30upx;
  }
}
.content {
  display: flex;
  flex-wrap: wrap;
  view {
    display: flex;
  }
  .row {
    width: 94%;

    margin: 0 3%;
    border-bottom: 1Px solid #ccc;
    .nominal {
      width: 30%;
      height: 120upx;
      font-weight: 200;
      font-size: 30upx;
      align-items: center;
    }
    .input {
      width: 70%;
      padding: 20upx 0;
      align-items: center;
      font-size: 30upx;
      &.switch {
        justify-content: flex-end;
      }
      .textarea {
        margin: 20upx 0;
        min-height: 120upx;
      }
    }
    .del {
      width: 100%;
      height: 100upx;
      justify-content: center;
	  margin-top: 60rpx;
      align-items: center;
      font-size: 36upx;
      color: #fff;
      background-color: #E64340;
      border-bottom: solid 1upx #eee;
    }
  }
  .last{
	  border-bottom: 0;
  }
}
</style>
